#include <cstdio>

int n, d[ 16 ], a[ 22 ][ 22 ], b[ 22 ][ 22 ];

void init( )
{
    int i, j;
    for ( i = 0; i <= 21; i++ )
        a[ 0 ][ i ] = a[ i ][ 0 ] = a[ 21 ][ i ] = a[ i ][ 21 ] = 0;
    scanf("%d", &n);
    for ( i = 0; i <= 15; i++ )
        scanf("%d", &d[ i ]);
    for ( i = 1; i <= 20; i++ )
        for ( j = 1; j <= 20; j++ )
            scanf("%d", &a[ i ][ j ]);
}

void work( )
{
    int i, j, s;
    while ( n-- )
    {
        for ( i = 1; i <= 20; i++ )
            for ( j = 1; j <= 20; j++ )
            {
                s = a[ i ][ j ] + a[ i - 1 ][ j ] + a[ i + 1 ][ j ] + a[ i ][ j - 1 ] + a[ i ][ j + 1 ];
                b[ i ][ j ] = a[ i ][ j ] + d[ s ];
                if ( b[ i ][ j ] < 0 )
                    b[ i ][ j ] = 0;
                if ( b[ i ][ j ] > 3 )
                    b[ i ][ j ] = 3;
            }
        for ( i = 1; i <= 20; i++ )
            for ( j = 1; j <= 20; j++ )
                a[ i ][ j ] = b[ i ][ j ];
    }
}

void print( )
{
    int i, j;
    for ( i = 1; i <= 20; i++ )
    {
        for ( j = 1; j <= 20; j++ )
        {
            if ( a[ i ][ j ] == 0 )
                printf(".");
            if ( a[ i ][ j ] == 1 )
                printf("!");
            if ( a[ i ][ j ] == 2 )
                printf("X");
            if ( a[ i ][ j ] == 3 )
                printf("#");
        }
        printf("\n");
    }
}

int main( )
{
    int t;
    scanf("%d", &t);
    while ( t-- )
    {
        init( );
        work( );
        print( );
        if ( t )
            printf("\n");
    }
    return 0;
}
